<template>
  <div class="px-2">
    <div class="d-flex w-100 justify-space-between">
      <input
        v-for="(item, index) in codes"
        :key="index"
        v-model="codes[index]"
        @input="handleInput(index, $event)"
        @keydown="handleKeyDown(index, $event)"
        @paste="handlePaste"
        inputmode="numeric"
        maxlength="1"
        type="number"
        oninput="if(value.length=1)value=value.slice(0,1)"
        class="text-center rounded font-size-20 font-weight-500 line-height-120 verificationCodes"
      />
    </div>
    <div v-if="errMsg" class="err-msg font-size-12 font-weight-400 line-height-120 text-primary-x mt-2">
      {{ errMsg }}
    </div>
  </div>
</template>
<script setup>
import { nextTick, ref } from 'vue'

defineProps({
  errMsg: { type: String, default: '' },
})
const emits = defineEmits(['update:modelValue'])

// 驗證值6碼
const codes = ref(['', '', '', '', '', ''])

const handleInput = (index, event) => {
  const value = event.target.value
  codes.value[index] = value

  // 輸入驗證碼的值
  emits('update:modelValue', codes.value.join(''))

  // 自動跳下一個輸入匡
  if (value && index < codes.value.length - 1) {
    const nextInput = event.target.nextElementSibling
    if (nextInput) {
      nextTick(() => {
        nextInput.focus()
      })
    }
  }
}
const handleKeyDown = (index, event) => {
  // 清空輸入匡的值
  if (event.key === 'Backspace' && !event.target.value && index > 0) {
    const prevInput = event.target.previousElementSibling
    if (prevInput) {
      nextTick(() => {
        prevInput.focus()
        codes.value[index - 1] = ''
        emits('update:modelValue', codes.value.join(''))
      })
    }
  }
}
const handlePaste = (event) => {
  event.preventDefault()
  const pasteData = event.clipboardData.getData('text/plain').trim()
  if (pasteData.length !== 6 || !/^\d+$/.test(pasteData)) {
    return
  }

  for (let i = 0; i < pasteData.length; i++) {
    codes.value[i] = pasteData[i]
  }

  emits('update:modelValue', codes.value.join(''))
}
</script>
<style lang="scss" scoped>
.verificationCodes {
  width: 3rem;
  height: 3rem;
  background-color: #333546;
}
input:focus-visible {
  outline: none;
}
/* Chrome, Safari, Edge, Opera */
input[type='number']::-webkit-outer-spin-button,
input[type='number']::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
/* Firefox */
input[type='number'] {
  -moz-appearance: textfield;
}
</style>
